package singsong;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class SongFileWriter {
	
	public void write(Song song, File file) throws FileNotFoundException {
		String baseFilename = getBaseFilename(file.getName());
		PrintWriter writer = new PrintWriter(file);
		int trackNum = 0;
		for (Track track : song.getTracks()) {
			String trackFilename = getTrackFilename(baseFilename, trackNum);
			writeTrackDataFile(track.getData(), new File(file.getParent(), trackFilename));
			writer.printf("%s, %s, %s\n", track.getName(), track.getInstrument(), trackFilename);
			++trackNum;
		}
		writer.close();
	}
	
	private String getBaseFilename(String filename) {
		int extensionIndex = filename.lastIndexOf(".");
		if (extensionIndex == -1) {
			return filename;
		} else {
			return filename.substring(0, extensionIndex);
		}
	}

	private String getTrackFilename(String baseFilename, int trackNum) {
		return baseFilename + String.format(".trackdata%02d", trackNum);
	}
	
	public void writeTrackDataFile(TrackData data, File file) throws FileNotFoundException {
		PrintWriter writer = new PrintWriter(file);
		writer.printf("%.02f\n", data.getSampleRate());
		for (TrackData.Sample sample : data.getSamples()) {
			writer.printf("%.06f, %.06f\n", sample.getFrequency(), sample.getVolume());
		}
		writer.close();
	}
}
